#ifndef __WMAIN_CPP__
#define __WMAIN_CPP__

#include "wmain.h"
#include <dlfcn.h>
#define EXTFILENAME "./build/libwext.so"
#define INITEXT "InitExt"
#define EXTFUNCTION "ExtFunction"

void HandleMessage(struct WServer::MsgHandle::wmsgdata* msg)
{
	int cround = 0;
	if (msg->clientindex > maxconn) {
		delete msg;return;
	}
	switch (msg->type) {
		case WMSG_ACCEPTCONNECT: {
			clientlist[msg->clientindex].main_tid = getCurrentRound();
			wserPrintMsg("set clientindex:%d to main_tid:%d\n", msg->clientindex, clientlist[msg->clientindex].main_tid);
			MsgAcceptConnect msgac;CreateMessage2WMysql(msg->clientindex, msgac);
			delete msg;msg = NULL;
			break;
		}
		default:
			cround = clientlist[msg->clientindex].main_tid;
			servermsglist[cround].push_back(msg);
			return; //don't delete msg!
	}
}

void* pdlExt;
void (*pExtFun)(struct wmsgdata*);
void (*pInitExt)();

void* ExtMsgHandle(void* args)
{
	pthread_detach(pthread_self());
	wserPrintMsg("ExtMsgHandle. pid:%d\n", syscall(SYS_gettid));
	int inc = (long)args;

	wmsgdata* msg;
	while (1) {
		do {
			msg = WServer::MsgQueue::PopMessage(inc);
			if (msg == 0) break;
			pExtFun(msg);
		}
		while (true);
		usleep(10);
	}
}

int main(int argc, char *argv[])
{
	int ret = EXIT_SUCCESS;
	pthread_t pid;
	int* portlist;

	moduleindex = MODULE_WMAIN;

	pdlExt = dlopen(EXTFILENAME, RTLD_NOW);
	if (!pdlExt) {
		printf("Can't find %s!!\n dlopen()Err:%s\n", EXTFILENAME,dlerror());
		goto exitpos;
	}

	wserInit(moduleindex);

	pInitExt = (void(*)())dlsym(pdlExt, INITEXT);
	if (!pInitExt) {
		printf("Can't find %s!!\n", INITEXT);
		goto exitpos;
	}
	pInitExt();
	pExtFun = (void(*)(struct WServer::MsgHandle::wmsgdata*))dlsym(pdlExt, EXTFUNCTION);
	if (!pExtFun) {
		printf("Can't find %s!!\n", EXTFUNCTION);
		goto exitpos;
	}

	for (int i = 0;i < GData::maxconn;i++) {
		initSocketData(i);
	}
	portlist = new int[GData::msgextthreadcount];
	for (int i = 0;i < GData::msgextthreadcount;i++) portlist[i] = i;
	for (int i = 0;i < GData::msgextthreadcount;i++) {
		pthread_create(&pid, 0, ExtMsgHandle, (void*)(intptr_t)portlist[i]);
	}
	delete[] portlist;

	while (1) {
		sleep(60);
	}

exitpos:
	wserUninit();
	return ret;
}

#endif //__WMAIN_CPP__
